package com.wangsd.web.face.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.JsonObject;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.utils.HttpClientUtils;
import com.wangsd.web.MyController;
import com.wangsd.web.face.entity.Agent;
import com.wangsd.web.face.entity.Merchant;
import com.wangsd.web.face.entity.Receiver;
import com.wangsd.web.face.service.MerchantReceiverService;
import com.wangsd.web.face.service.MerchantService;
import com.wangsd.web.face.service.StoreService;
import com.wangsd.web.sys.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author generator
 * @since 2019-09-10
 */
@Api(value = "merchant", tags = "商户管理")
@RestController
@RequestMapping("/face/merchant")
public class MerchantController extends MyController {

    @Autowired
    MerchantService merchantService;
    @Autowired
    MerchantReceiverService merchantReceiverService;
    @Autowired
    StoreService storeService;
    @Value("${service.authApiUrl}")
    private String wechatUrl;

    @ApiOperation(value = "查询商户列表", notes = "查询商户列表", httpMethod = "POST")
    @RequestMapping(value = "/selectList/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public Result<IPage<Merchant>> selectList(@ApiParam(value = "当前页", required = true) @PathVariable("pageNum") Integer pageNum,
                                              @ApiParam(value = "每页大小", required = true) @PathVariable("pageSize") Integer pageSize,
                                              @RequestBody @ApiParam(name = "params", value = "传入json格式") Merchant params) {
        SysUser loginUser = getUserInfo();
        IPage<Merchant> resultIPage = merchantService.selectList(pageNum, pageSize, params, loginUser.getCode());
        return Result.success(resultIPage);
    }


    @ApiOperation(value = "新增或修改商户", notes = "新增或修改商户", httpMethod = "POST", response = Result.class)
    @RequestMapping(value = "addOrUpdate", method = RequestMethod.POST)
    public Result addOrUpdate(Merchant params) {
        merchantService.addOrUpdate(params);
        return Result.success();
    }

    @ApiOperation(value = "删除商户信息", notes = "删除商户信息", httpMethod = "GET", response = Result.class)
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public Result delete(@ApiParam(value = "用户id", required = true) @PathVariable("id") Long id) {
        Integer count = storeService.selectCountByMerchantId(id);
        if (count > 0) {
            return Result.fail("必须先删除门店");
        }
        merchantService.removeById(id);
        return Result.success();
    }

    @ApiOperation(value = "通过id查询商户", notes = "通过id查询商户", httpMethod = "GET", response = Result.class)
    @GetMapping("/selectById/{id}")
    public Result<Merchant> selectById(@ApiParam(value = "商户id", required = true) @PathVariable Long id) {
        Merchant result = merchantService.getById(id);
        return Result.success(result);
    }

    @ApiOperation(value = "查询所有商户", notes = "查询所有商户", httpMethod = "GET", response = Result.class)
    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    public Result selectAll() {
        SysUser loginUser = getUserInfo();
        List<Map> list = merchantService.selectAllByUserCode(loginUser.getCode());
        return Result.success(list);
    }

    @ApiOperation(value = "通过id查询商戶分账账户", notes = "通过id查询商戶分账账户", httpMethod = "GET", response = Result.class)
    @GetMapping("/selectReceiverById/{id}")
    public Result selectReceiverById(@ApiParam(value = "商户id", required = true) @PathVariable Long id) {
        List<Receiver> list = merchantService.selectMerchantReceivers(id);
        return Result.success(list);
    }

    @ApiOperation(value = "新增分账账户", notes = "新增分账账户", httpMethod = "POST", response = Result.class)
    @RequestMapping(value = "addMerchantReceiver", method = RequestMethod.POST)
    public Result addMerchantReceiver(@ApiParam(value = "商户id", required = true) @RequestParam Long merchantId,
                                      @ApiParam(value = "分账账户id", required = false) @RequestParam Long receiverId,
                                      @ApiParam(value = "总抽成金额", required = true) @RequestParam Long drawTotalFee,
                                      @ApiParam(value = "单笔订单多少起抽", required = true) @RequestParam Long minimumDraw,
                                      @ApiParam(value = "每个分账账号分多少", required = true) @RequestParam Long perDraw) {
        try {
            Integer count = merchantReceiverService.selectByMerchantAndReceiverId(merchantId, receiverId);
            if (count > 0) {
                return Result.fail("此商户已存在当前分账账户！");
            }
            merchantService.addReceiver(merchantId, receiverId, drawTotalFee, minimumDraw, perDraw);
            return Result.success();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除分账账户", notes = "删除分账账户", httpMethod = "POST", response = Result.class)
    @RequestMapping(value = "delMerchantReceiver", method = RequestMethod.POST)
    public Result delMerchantReceiver(@ApiParam(value = "商户id", required = true) @RequestParam Long merchantId, @ApiParam(value = "分账账户id", required = true) @RequestParam Long receiverId) {
        return merchantService.delMerchantReceiver(merchantId, receiverId);
    }

    @ApiOperation(value = "关联公众号和小程序", notes = "关联公众号和小程序", httpMethod = "GET", response = Result.class)
    @GetMapping("/bindGzhAndXcx/{id}")
    public Object bindGzhAndXcx(@ApiParam(value = "商户id", required = true) @PathVariable Long id) {
        if (id == null) {
            return Result.fail("商户id不能未空");
        }
        Merchant merchant = merchantService.getById(id);
        if (merchant == null) {
            return Result.fail("商户信息异常");
        }
        String url = wechatUrl + "/api/open/bind";
        Map<String, String> params = new HashMap<>();
        params.put("merchantId", id + "");
        params.put("platform", "face");
        params.put("appid", merchant.getSubAppId());
        params.put("miniAppid", merchant.getMiniAppid());
        params.put("appSecret", merchant.getAppSecret());
        String str = HttpClientUtils.get(url, params, "UTF-8");
        JSONObject json = JSONObject.parseObject(str);
        //保存关联状态
        if (json.getInteger("code") == 200) {
            Merchant upMerchant = new Merchant();
            upMerchant.setIsRelation(1);
            upMerchant.setId(merchant.getId());
            merchantService.saveOrUpdate(upMerchant);
        }
        return str;
    }
}

